using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks.Dataflow;
using System;
using System.Collections.Generic;
namespace TPL
{
    public class SegmentBlock
    {
        private readonly byte[] _pattern;
       

        public SegmentBlock(byte[] pattern)
        {
           
            _pattern = (byte[])pattern.Clone();
            List<byte> LastBuffer = new List<byte>(); // 缓存区，存储未处理的数据
            List<byte> accumulatedFrames = new List<byte>(); // 用于积累帧数据的缓存区
            _Process = new ActionBlock<byte[]>(buffer =>//进行分帧处理
            {
               
                   
                        //LastBuffer.AddRange(LastBuffer);
                        LastBuffer.AddRange(buffer);

                        while (true)
                        {
                            var temp = LastBuffer.ToArray().AsSpan();
                            var result = temp.IndexOf(_pattern);

                            if (result != -1)
                            {
                                accumulatedFrames.AddRange(temp[0..result].ToArray());
                                if (accumulatedFrames.Count > 0)
                                {
                                    byte[] frame = accumulatedFrames.ToArray();
                                    DataArrived?.Invoke(frame);//发送完整的一帧
                                    accumulatedFrames.Clear();
                                }
                                LastBuffer.RemoveRange(0, result + _pattern.Length);
                            }
                            else
                            {
                                LastBuffer.RemoveRange(0, (temp.Length - _pattern.Length + 1));
                                accumulatedFrames.AddRange(temp[0..(temp.Length - _pattern.Length + 1)].ToArray());
                                break;
                            }
                        }
                    
                //// 添加最后一帧的处理
                //if (buffer.Length <= _pattern.Length)
                //{
                //    accumulatedFrames.AddRange(LastBuffer);
                //    LastBuffer.Clear();
                //    byte[] frame1 = accumulatedFrames.ToArray();
                //    DataArrived?.Invoke(frame1);
                //}

            });
        }
        public void Enqueue(byte[] buffer)
        {
            _Process.Post(buffer);//向分帧模块传入从文件读取的数据块
        }
        
        public ActionBlock<byte[]> _Process;
        
        public Action<byte[]> DataArrived;

    }
}



  



















